<template>
  <div>
    <!-- 标题 -->
    <mu-base-title :title="`${$route.params._id ? '编辑' : '添加'}服务信息`" />

    <!-- 居民信息 -->
    <div class="mu-small-title ">居民信息</div>
    <mu-resident-info ref="muResidentInfoRef" v-model:form-data="residentData" :isShowSelectName="!$route.params._id" />

    <!-- 服务信息 -->
    <div class="mu-small-title ">服务信息</div>
    <mu-info-service ref="muInfoRef" v-model:form-data="serviceDetailData" />

    <!-- 按钮 -->
    <div class="mu-btn-box-top-style">
      <el-button type="primary" @click="onConfirmBtnClick">提交审核</el-button>
      <el-button @click="$router.back()">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { updateResidentApi } from '@/api/resident';
import { addServiceApi, getServicesDetailApi, updateServiceApi } from '@/api/serviceManage';
import { onMounted, ref, useTemplateRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route: any = useRoute();
const router: any = useRouter();

const muResidentInfoRef = useTemplateRef('muResidentInfoRef');
const muInfoRef = useTemplateRef('muInfoRef');

const serviceDetailData: any = ref({});
const residentData: any = ref({});

onMounted(() => {
  if (route.params._id) {
    getServicesDetail(route.params._id);
  }
})

const getServicesDetail = async (_id: string) => {
  const res = await getServicesDetailApi({ _id });
  console.log('服务详情数据：', res);
  if (res.code == 200) {
    residentData.value = res.data.residentId ?? {};
    serviceDetailData.value = {
      ...res.data
    };
  }
};

const onConfirmBtnClick = async () => {
  // 表单验证是否通过
  const muResidentInfoResult = await muResidentInfoRef.value?.onSubmit();
  const muInfoResult = await muInfoRef.value?.onSubmit();
  if (muResidentInfoResult && muInfoResult) {
    // 修改用户数据
    updateResident();
  }
};

const updateResident = async () => {
  const res = await updateResidentApi({
    ...residentData.value,
    _id: route.params._id ? residentData.value._id : residentData.value.residentId
  });
  if (res.code == 200) {
    ElMessage.success('居民信息修改成功');
    if (route.params._id) {
      updateService();
    } else {
      addService();
    }
  } else if (res.code == 500) {
    if (route.params._id) {
      updateService();
    } else {
      addService();
    }
  } else {
    ElMessage.error(res.message);
  }
}

const addService = async () => {
  const res = await addServiceApi({
    ...serviceDetailData.value,
    residentId: residentData.value.residentId
  });

  console.log(res);

  if (res.code == 200) {
    ElMessage.success('服务信息添加成功');
    router.back();
  } else {
    ElMessage.error(res.message);
  }
}

const updateService = async () => {
  const res = await updateServiceApi({
    ...serviceDetailData.value,
    residentId: residentData.value._id
  });
  if (res.code == 200) {
    ElMessage.success('服务信息修改成功');
    router.back();
  } else {
    ElMessage.error(res.message);
  }
};
</script>

<style scoped></style>